package com.rrjjg.app.mybatis.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rrjjg.app.mybatis.bean.MyBatisConditional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Optional;


/**
 * ----------------------------------------------------------------------------- <br>
 * 功能 :  <br>
 * ----------------------------------------------------------------------------- <br>
 * 作者 : Vayne <br>
 * 时间 : 2023/4/8 <br>
 */
@Slf4j
public class ConditionalBuilder<E> {

    QueryWrapper<E> query;
    E e;
    Class<E> c;

    public ConditionalBuilder(E e, Class<E> c) {
        this.e = e;
        this.c = c;
        query = Wrappers.query();
    }

    public  QueryWrapper<E> wrapper(){
        reflex();
        return query;
    }

    /**
     * ----------------------------------------------------------------------------- <br>
     * 功能 : 反射获取对象
     * 作者 : Vayne <br>
     * 时间 : 2023/4/8 <br>
     * ----------------------------------------------------------------------------- <br>
     */
    private void reflex()  {
        try{
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                MyBatisConditional annotation = field.getAnnotation(MyBatisConditional.class);
                if(annotation!=null){
                    String alias = annotation.alias();
                    String name = StringUtils.hasLength(alias)?alias:field.getName();
                    Object o = field.get(e);
                    if(Optional.ofNullable(o).isPresent()) {
                        switch (annotation.type()) {
                            case EQ -> query.eq(name, o);
                            case IN -> query.in(name, o);
                            case LIKE_RIGHT -> query.likeRight(name, o);
                            case LIKE -> query.like(name, o);
                        }
                    }
                }
            }
        }catch (Exception ex){
            log.error("reflex is error ",e);
        }
    }



}
